<?php
/**
 * 个人预约-订单
 *
 * User: kaikaic
 * Date: 2018/10/28
 * Time: 20:52
 */

namespace app\exam\controller;

use app\exam\service\AccountService;
use app\exam\service\EnterpriseService;
use app\exam\service\MecService;
use app\exam\service\MecSetService;
use app\exam\service\MessageService;
use app\exam\service\OrderService;
use app\exam\service\ReportService;
use controller\BasicAdmin;
use service\ConfigService;
use think\Db;
use PHPExcel;

class Order extends BasicAdmin {

    protected $table = "ExamOrder";

    public function index() {
    $this->title = "个人预约";

    $query = array();
    $query['exam_name'] = $this->request->get("examname");
    $query['exam_idCard'] = $this->request->get("idCard");

    $query['order_status'] = intval($this->request->get("order_status"));
    $query['pay_status'] = intval($this->request->get("pay_status"));
    $query['mec_id'] = intval($this->request->get("mec_id"));

    $db = Db::name($this->table);

     $db->where('type',1);
        if ($query['exam_name']) {
            $db->whereLike("exam_name", "%{$query['exam_name']}%");
        }
        if ($query['exam_idCard']) {
            $db->whereLike("exam_idCard", "%{$query['exam_idCard']}%");
        }
    if ($query['mec_id']) {
        $db->where(['mec_id'=>$query['mec_id']]);
    }
    if ($query['order_status']) {
        $db->where(['order_status'=>$query['order_status']]);
    }
        if ($query['pay_status']) {
            $db->where(['pay_status'=>$query['pay_status']]);
        }
    return parent::listRecord($db, "", true, "id desc");
}
    public function groupindex() {
        $this->title = "团检预约";

        $query = array();
//        $query['name'] = $this->request->get("name");
        $query['order_status'] = intval($this->request->get("order_status"));
        $query['mec_id'] = intval($this->request->get("mec_id"));
        $query['order_sn'] = $this->request->get("order_sn");
        $query['start_date'] = $this->request->get("start_date");
        $query['end_date'] = $this->request->get("end_date");
        $query['enterprise_id'] = $this->request->get("enterprise_id");

        $db = Db::name($this->table);
        $db->where('group_id','gt',0);
        if ($query['order_sn']) {
            $db->whereLike("order_sn", "%{$query['order_sn']}%");
        }
        if ($query['mec_id']) {
            $db->where(['mec_id'=>$query['mec_id']]);
        }
        if ($query['order_sn']) {
            $db->whereLike('order_sn','%'.$query['order_sn'].'%');
        }
        if ($query['start_date']) {
            $db->where('exam_date','gt',$query['start_date']);
        }
        if ($query['end_date']) {
            $db->where('exam_date','lt',$query['end_date']);
        }
        if ($query['enterprise_id']) {
            $db->where(['enterprise_id'=>$query['mec_id']]);
        }
        return parent::listRecord($db, "", true, "id desc");
    }
    /**
     * 预约确认
     *
     * return array('1'=>'预约中', '2'=>'已预约', '3'=>'已参检', '4'=>'已完成', '10'=>'已取消', '11'=>'预约失败');
     */
    public function confirm() {
        $id = intval($this->request->param('id'));
        if (empty($id)) {
            $this->error('参数错误，请稍候再试！');
        }

        $record = OrderService::getInstance()->find($id);
        if (empty($record)) {
            $this->error('记录不存在，请重新操作!');
        }

        if ($record['order_status'] != 1) {
            $this->error('状态错误，订单已处理！');
        }
        if ($record['pay_status'] != 2) {
            $this->error('状态错误，订单还没支付！');
        }

        if ($this->request->isGet()) {
            $account = AccountService::getInstance()->single(array('id'=>$record['account_id']));
            if (!$account) {
                $this->error('数据错误，没有这个用户！');
            }
            $record['user_name'] = $account['real_name'];
            $record['identity_card'] = $account['identity_card'];

            return view('confirm', [
                'title'=>'预约确认',
                'vo'=>$record,
            ]);
        }

        if ($this->request->isPost()) {
            $verify = intval($this->request->post("ok"));
            $comment = trim($this->request->post("comment"));

            $status = 0;
            if ($verify == 1) {
                $status = 2;
            }else if ($verify == 2) {
                $status = 11;
            }
            if (!$status) {
                $this->error('参数错误，请稍候再试！');
            }

            $update = array();
            $update['order_status'] = $status;
            $update['comment'] = $comment;
            $result = OrderService::getInstance()->update($update, $id);
            if ($result) {
                $type = true;
                if ($status == 11) {
                    $type = false;
                }

                $record['comment'] = $update['comment'];
                $this->sendOrderMessage($record['account_id'], $record, $type);

                $this->success('操作完成！', '');
            }else {
                $this->error('操作失败，请稍候再试！');
            }
        }
    }

    /**
     * 列表数据处理
     */
    protected function _index_data_filter(&$data) {
        $size = count($data);
        $orderStatus = ConfigService::examOrderStatus();
        $orderPayStatus = ConfigService::examOrderPayStatus();

        $mecList = MecService::getInstance()->listMec();
        $count = OrderService::getInstance()->count('order_status=1 and pay_status=2');
        $this->assign("count",$count);
        for ($i=0; $i<$size; $i++) {
            $temp = $data[$i];

            $account = AccountService::getInstance()->single(array('id'=>$temp['account_id']));
            if (!$account) {
                continue;
            }
            $temp['user_name'] = $account['real_name'];
            $temp['identity_card'] = $account['identity_card'];

            $mec = MecService::getInstance()->single(array('id'=>$temp['mec_id']));
            if (!isset($mecList[$temp['mec_id']])) {
                continue;
            }
            $temp['mec_txt'] = $mecList[$temp['mec_id']];
            $setidarr = explode(",",$temp['set_id']);
            $temp['set_txt'] = '';
            foreach ($setidarr as $key){
                $set = MecSetService::getInstance()->single(array('id'=>$key));
                if (!$set) {
                    continue;
                }
                $temp['set_txt'] .= $set['name'];
            }

            $temp['type_txt'] = "";
            if ($temp['type'] == 1) {
                $temp['type_txt'] = "个人";
            }
            if ($temp['type'] == 2) {
                $temp['type_txt'] = "团体";
            }

            // 是否有体检报告
            $temp['report'] = 0;
            $report = ReportService::getInstance()->single(array('order_sn'=>$temp['order_sn']));
            if ($report) {
                $temp['report'] = 1;
            }

            $temp['order_status_txt'] = $orderStatus[$temp['order_status']];
            $temp['pay_status_txt'] = $orderPayStatus[$temp['pay_status']];

            $data[$i] = $temp;
        }

        $this->assign('order_status', $orderStatus);
        $this->assign('pay_status', $orderPayStatus);
        $this->assign("mec_list", $mecList);
    }
    protected function _groupindex_data_filter(&$data) {
        $size = count($data);
        $orderStatus = ConfigService::examOrderStatus();
        $orderPayStatus = ConfigService::examOrderPayStatus();
        $enterprise=EnterpriseService::getInstance()->listEnterprise();
        $mecList = MecService::getInstance()->listMec(1);

        for ($i=0; $i<$size; $i++) {
            $temp = $data[$i];

            $account = AccountService::getInstance()->single(array('id'=>$temp['account_id']));
            if (!$account) {
                continue;
            }
            $temp['user_name'] = $account['real_name'];
            $temp['identity_card'] = $account['identity_card'];

            $mec = MecService::getInstance()->single(array('id'=>$temp['mec_id']));
            if (!isset($mecList[$temp['mec_id']])) {
                continue;
            }
            $temp['mec_txt'] = $mecList[$temp['mec_id']];
            $temp['enterprise_txt'] = $enterprise[$temp['enterprise_id']];
            $setidarr = explode(",",$temp['set_id']);
            $temp['set_txt'] = '';
            foreach ($setidarr as $key){
                $set = MecSetService::getInstance()->single(array('id'=>$key));
                if (!$set) {
                    continue;
                }
                $temp['set_txt'] .= $set['name'];
            }

            $temp['type_txt'] = "";
            if ($temp['type'] == 1) {
                $temp['type_txt'] = "个人";
            }
            if ($temp['type'] == 2) {
                $temp['type_txt'] = "团体";
            }

            // 是否有体检报告
            $temp['report'] = 0;
            $report = ReportService::getInstance()->single(array('order_sn'=>$temp['order_sn']));
            if ($report) {
                $temp['report'] = 1;
            }

            $temp['order_status_txt'] = $orderStatus[$temp['order_status']];
            $temp['pay_status_txt'] = $orderPayStatus[$temp['pay_status']];

            $data[$i] = $temp;
        }

        $this->assign('enterprise', $enterprise);
        $this->assign('order_status', $orderStatus);
        $this->assign('pay_status', $orderPayStatus);
        $this->assign("mec_list", $mecList);
    }

    public function export(){
        if ($this->request->isGet()) {
            $orderStatus = ConfigService::examOrderStatus();
            $orderPayStatus = ConfigService::examOrderPayStatus();
            $gid =  $this->request->param('gid',0);
            $mecList = MecService::getInstance()->listMec($gid);
            return view('export', [
                'title'=>'导出订单',
                'group_id'=>$gid,
                'order_status'=>$orderStatus,
                'pay_status'=>$orderPayStatus,
                'mec_list'=>$mecList,
            ]);
        }
        $query = array();
//        $query['name'] = $this->request->get("name");
        $query['order_status'] = intval($this->request->post("order_status"));
        $query['mec_id'] = intval($this->request->post("mec_id"));
        $query['order_sn'] = $this->request->post("order_sn");
        $query['exam_idCard'] = $this->request->post("exam_idCard");
        $query['start_time'] = $this->request->post("start_time");
        $query['end_time'] = $this->request->post("end_time");
        $query['group_id'] = $this->request->post("group_id");

        $db = Db::name($this->table);

        if($query['group_id']==1){
            $db->where('group_id','gt',0);
        }else{
            $db->where('group_id',0);
        }

//        if ($query['name']) {
//            $db->whereLike("name", "%{$query['name']}%");
//        }
        if ($query['mec_id']) {
            $db->where(['mec_id'=>$query['mec_id']]);
        }
        if ($query['order_sn']) {
            $db->whereLike('order_sn','%'.$query['order_sn'].'%');
        }
        if ($query['order_status']) {
            $db->where(['order_status'=>$query['order_status']]);
        }
        if ($query['exam_idCard']) {
            $db->whereLike('exam_idCard','%'.$query['exam_idCard'].'%');
        }
        if ($query['start_time']) {
            $db->whereLike('exam_date','gt',$query['start_time']);
        }
        if ($query['end_time']) {
            $db->whereLike('exam_date','lt',$query['end_time']);
        }
        $excelRecords = $db->select();
        $this->doExportAction($excelRecords,$query['group_id'] );
    }

    /**
     * 删除-体检中心
     */
    public function returnmoney() {
        $id = intval($this->request->post('id', ''));
        if (empty($id)) {
            $this->error('参数错误!');
        }

        $order = OrderService::getInstance()->find($id);
        if (empty($order)) {
            $this->error('记录不存在，请重新操作!');
        }
        $update = array();
        $update['order_status'] = 10;
        $update['pay_status'] = 3;

        $result = OrderService::getInstance()->update($update, $id);
        if ($result) {
            $type = 1;
            $title = "退款成功";
            $mec = MecService::getInstance()->single(array('id'=>$order['mec_id']));
            if (!$mec) {
                return false;
            }
            $set = MecSetService::getInstance()->single(array('id'=>$order['set_id']));
            if (!$set) {
                return false;
            }
            $content = "";
            $content .= "您的体检预约：" . "<br/>";
            $content .= "体检中心:" . $mec['name'] . "<br/>";
            $content .= "体检套餐:" . $set['name'] . "<br/>";
            $content .= "体检时间:" . $order['exam_date'] . "<br/>";
            $content .= "退款成功" . "<br/>";
            MessageService::getInstance()->sendOrderMessage($order['account_id'], $type, $title, $content);
            $this->success('退款成功!', '');
        }else {
            $this->error('退款失败，请重新再试!');
        }
    }
/**
 * 数据导出
 * @param $excelRecords
 * @throws \PHPExcel_Exception
 * @throws \PHPExcel_Reader_Exception
 */
public function doExportAction($excelRecords,$gid) {
    $objExcel = new PHPExcel();
    $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');

    // 设置水平垂直居中
    $objExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
    // 字体和样式
    $objExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(10);
    $objExcel->getActiveSheet()->getStyle('A2:AB2')->getFont()->setBold(true);
    $objExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);

    // 第一行、第二行的默认高度
    $objExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30);
    $objExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20);

    //设置某一列的宽度
    $objExcel->getActiveSheet()->getColumnDimension('A')->setWidth(30);
    $objExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
    $objExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
    $objExcel->getActiveSheet()->getColumnDimension('D')->setWidth(50);
    $objExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
    $objExcel->getActiveSheet()->getColumnDimension('F')->setWidth(25);
    $objExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
    $objExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
    $objExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
    // 设置表头
    // 合并
    $objExcel->getActiveSheet()->mergeCells('A1:I1');
    $objActSheet = $objExcel->getActiveSheet(0);

    //设置excel的标题
    $objActSheet->setTitle('订单统计');
    $objActSheet->setCellValue('A1','订单统计');
    $objActSheet->setCellValue('A2','订单号');
    $objActSheet->setCellValue('B2','客户姓名');
    $objActSheet->setCellValue('C2','客户身份证号');
    $objActSheet->setCellValue('D2','医院');
    $objActSheet->setCellValue('E2','套餐名');
    $objActSheet->setCellValue('F2','企业名');
    $objActSheet->setCellValue('G2','下单时间');
    $objActSheet->setCellValue('H2','订单状态');
    $objActSheet->setCellValue('I2','体检报告');
    $row = -1;
    $baseRow = 3; //数据从N-1行开始往下输出 这里是避免头信息被覆盖

    $orderStatus = ConfigService::examOrderStatus();
    $orderPayStatus = ConfigService::examOrderPayStatus();
    $mecList = MecService::getInstance()->listMec($gid);
    for ($i=0; $i<count($excelRecords); $i++) {
        $temp = $excelRecords[$i];
        $examinfo = Db::name('exam_enterprise')->find($temp['enterprise_id']);
        $mec = MecService::getInstance()->single(array('id'=>$temp['mec_id']));
        if (!isset($mecList[$temp['mec_id']])) {
            continue;
        }
        $temp['mec_txt'] = $mecList[$temp['mec_id']];
        $setidarr = explode(",",$temp['set_id']);
        $temp['set_txt'] = '';
        foreach ($setidarr as $key){
            $set = MecSetService::getInstance()->single(array('id'=>$key));
            if (!$set) {
                continue;
            }
            $temp['set_txt'] .= $set['name'];
        }
        // 是否有体检报告
        $temp['report'] = 0;
        $temp['reportvalue'] = '';
        $report = ReportService::getInstance()->single(array('order_sn'=>$temp['order_sn']));
        if ($report) {
            $temp['report'] = 1;
            $temp['reportvalue'] = $report['name'];
        }
        $temp['order_status_txt'] = $orderStatus[$temp['order_status']];
        $row = $baseRow + $i;
        $objExcel->getActiveSheet()->setCellValue('A'.$row, $temp['order_sn']);
        $objExcel->getActiveSheet()->setCellValue('B'.$row, $temp['exam_name']);
        $objExcel->getActiveSheet()->setCellValue('C'.$row, $temp['exam_idCard']);
        $objExcel->getActiveSheet()->setCellValue('D'.$row, $temp['mec_txt']);
        $objExcel->getActiveSheet()->setCellValue('E'.$row, $temp['set_txt']);
        $objExcel->getActiveSheet()->setCellValue('F'.$row, $examinfo['name']);
        $objExcel->getActiveSheet()->setCellValue('G'.$row, date('Y-m-d H:i',$temp['create_time']));
        $objExcel->getActiveSheet()->setCellValue('H'.$row, $temp['order_status_txt']);
        $objExcel->getActiveSheet()->setCellValue('I'.$row, $temp['reportvalue']);

    }
    // 输出
    $objExcel->setActiveSheetIndex(0);
    $fileName = "订单数据导出_" . date('Y-m-d') . ".xlsx";
    // type1: 保存文件
    // $objWriter->save($fileName);

    //type2: 输出
    header('Content-Type: applicationnd.ms-excel');
    header("Content-Disposition: attachment;filename={$fileName}");
    header('Cache-Control: max-age=0');
    $objWriter->save('php://output');
}
    /**
     * 发送预约消息
     */
    private function sendOrderMessage($accountID, $order, $flag=true) {
        if (!is_bool($flag)) {
            return false;
        }

        if ($flag === true) {
            $type = 1;
            $title = "恭喜您，预约成功";
        }else {
            $type = 2;
            $title = "很遗憾，预约失败";
        }

        $mec = MecService::getInstance()->single(array('id'=>$order['mec_id']));
        if (!$mec) {
            return false;
        }

        $set = MecSetService::getInstance()->single(array('id'=>$order['set_id']));
        if (!$set) {
            return false;
        }

        $content = "";
        $content .= "您的体检预约：" . "<br/>";
        $content .= "体检中心:" . $mec['name'] . "<br/>";
        $content .= "体检套餐:" . $set['name'] . "<br/>";
        $content .= "体检时间:" . $order['exam_date'] . "<br/>";

        if ($flag === true) {
            $content .= "预约成功,请9点之前达到" . "<br/>";
            $content .= "地址:" . $mec['address'] . "<br/>";
        }else {
            $content .= "预约失败" . "<br/>";
            $content .= "失败原因:" . $order['comment'];
        }

        MessageService::getInstance()->sendOrderMessage($accountID, $type, $title, $content);
    }
}

